package cl.ccs.migracionbcmc.util;

import java.io.BufferedInputStream;

import java.net.URL;
import java.net.URLConnection;


public class UtilFtpClient {
    private String ip;
    private String path;
    private String usuario;
    private String password;
    private String filename;

    private static UtilFtpClient instance;

    public static UtilFtpClient getInstance() {
        return instance == null ? new UtilFtpClient() : instance;
    }

    public void connect(String ip, String usuario, String password, String filename) {
        setIp(ip);
        setPath("");
        setUsuario(usuario);
        setPassword(password);
        setFilename(filename);
    }

    public void connect(String ip, String usuario, String password, String filename, String path) {
        connect(ip, usuario, password, filename);
        setPath(path);
    }

    public String getContent() {
        try {
            String strUrl =
                "ftp://" + getUsuario() + ":" + getPassword() + "@" + getIp() + getPath() + getFilename() + ";type=i";
            System.out.println("strUrl --> " + strUrl);
            URL url = new URL(strUrl);
            URLConnection con = url.openConnection();
            BufferedInputStream in = new BufferedInputStream(con.getInputStream());
            int i = 0;
            byte[] bytesIn = new byte[1024];
            String log = "";
            while ((i = in.read(bytesIn)) >= 0) {
                log += new String(bytesIn);
            }
            in.close();
            return log.trim();
        } catch (Exception e) {
            e.printStackTrace();
            return "Error : " + "\n" +  e.getMessage();
        }
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getIp() {
        return ip;
    }

    public void setPath(String path) {
        if (path ==null || path.trim().length()==0) {
            path = "/";
        }
        if (path.charAt(0) != '/') {
            path = "/" + path;
        }
        if (path.charAt(path.length() - 1) != '/') {
            path = path + "/";
        }
        this.path = path;
    }

    public String getPath() {
        return path;
    }

    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    public String getUsuario() {
        return usuario;
    }

    private void setPassword(String password) {
        this.password = password;
    }

    private String getPassword() {
        return password;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public String getFilename() {
        return filename;
    }
}
